package com.shz.appletsapi.config.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import com.shz.appletsapi.config.security.social.support.ZySpringSocialConfigurer;


@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {


	@Bean
	PasswordEncoder passwordEncoder(){
		return new BCryptPasswordEncoder();
	}
	
	@Autowired
	private UserDetailsService userDetailsService;
	
	@Autowired
	AuthenticationFailureHandler zyAuthenticationFailureHandler;
	
	@Autowired
	AuthenticationSuccessHandler zyAuthenticationSuccessHandler;
	
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		ZySpringSocialConfigurer configurer = new ZySpringSocialConfigurer("/auth");
		configurer.signupUrl("/regist.html");
		
		http.formLogin()
		.loginPage("/login.html")
		.loginProcessingUrl("/authentication/form")
		.successHandler(zyAuthenticationSuccessHandler)
		.failureHandler(zyAuthenticationFailureHandler)
		.and()
		.userDetailsService(userDetailsService)
		.authorizeRequests()
		.antMatchers("/login.html").permitAll()
		.antMatchers("/authentication/form").permitAll()
		.antMatchers("/auth/**").permitAll()
		.antMatchers("/signup").permitAll()
		.antMatchers("/regist.html").permitAll()
		.antMatchers("/registUser").permitAll()
		.anyRequest()
	    .authenticated()
	    .and().csrf().disable();
		http.apply(configurer);
	}


}
